package com.yj.ccs.abs.boot.authorization.interceptor;

import com.google.common.collect.Lists;
import com.yj.ccs.abs.boot.authorization.annotation.UserRole;
import com.yj.ccs.abs.boot.authorization.session.UserSession;
import com.yj.ccs.abs.common.enums.UserRoleType;
import com.yj.ccs.abs.common.exception.UserForbiddenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Copyright 2018 (C) Yunjian-VC
 * Created on : 2018/3/14
 * Author     : Unbelievable9
 **/
@Service
public class UserRoleInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    UserSession userSession;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;

            List<UserRoleType> userRoleTypeList = Stream.of(method.getMethodAnnotation(UserRole.class),
                    method.getBeanType().getDeclaredAnnotation(UserRole.class)).filter(Objects::nonNull)
                    .flatMap(a -> Lists.newArrayList(a.value()).stream())
                    .collect(Collectors.toList());

            if (userRoleTypeList.size() > 0) {
                if (userSession.getUser() != null &&
                        !userRoleTypeList.contains(userSession.getUser().getRole_type())) {
                    throw new UserForbiddenException();
                }
            }
        }

        return super.preHandle(request, response, handler);
    }
}
